package com.itcast.demo.single;

/**
 * Created by qiyei2015 on 2017/5/13.
 */
public class Instance {
    private String str = "";
    private int a = 0;

    private static Instance ins = null;
//    private volatile static Instance ins = null;
    /**
     * 构造方法私有化
     */
    private Instance(){
        str = "hello";
        a = 20;
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * DCL方式获取单例
     * @return
     */
    public static Instance getInstance(){
        if (ins == null){
            synchronized (Instance.class){
                if (ins == null){
                    ins = new Instance();
                }
            }
        }
        return ins;
    }

    public static void main(String[] args) {
        int a = 1;
        int b = 1;
        // \u000a a = 2;
        // \u000d b = 2;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
       /* for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                System.out.println("hello world！" );
            }).start();
            new Thread(){
                public void run(){
                    System.out.println("hello world！" );
                }
            }.start();

            new Thread() {
                public void run() {
                    System.out.println("匿名内部类创建线程方式1...");
                    Instance instance = Instance.getInstance();
                    System.out.println("instance = " + instance);
                };
            }.start();

            //方式2:实现Runnable,Runnable作为匿名内部类
            new Thread(new Runnable() {
                public void run() {
                    System.out.println("匿名内部类创建线程方式2...");
                    Instance instance2 = Instance.getInstance();
                    System.out.println("instance2 = " + instance2);
                }
            } ).start();

            // 同上，使用lambda表达式函数式编程
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " is running");
                Instance instance3 = Instance.getInstance();
                System.out.println("instance3 = " + instance3);
            }).start();
        }
*/
//        Instance instance = Instance.getInstance();
//        System.out.println("instance = " + instance);
//        Instance instance2 = Instance.getInstance();
//        System.out.println("instance2 = " + instance2);
    }

}
